<template>
  <LoginLayout>
    <template #form>
      <p class="mb-8 text-base font-[500] lg:text-2xl lg:font-[600]">{{ $mt('SIGN IN') }}</p>
      <div class="mb-5">
        <van-form ref="formRef">
          <div class="mb-2.5 rounded-3xl bg-input-color py-0.5 lg:mx-auto lg:mb-5 lg:w-[80%] lg:py-0.5">
            <van-field
              v-model="formData.email"
              name="email"
              :placeholder="$mt('Email')"
              :rules="[
                {
                  required: true,
                  trigger: 'onSubmit',
                  message: $mt('Please enter a valid email address'),
                },
                {
                  pattern,
                  message: $mt('Please enter a valid email address'),
                  trigger: 'onSubmit',
                },
              ]">
              <template #left-icon>
                <van-icon name="user-circle-o" size="22px" color="#fff" />
              </template>
            </van-field>
          </div>
          <div class="rounded-3xl bg-input-color py-0.5 lg:mx-auto lg:w-[80%] lg:py-0.5">
            <van-field
              v-model="formData.password"
              type="password"
              name="password"
              :placeholder="$mt('Password')"
              :rules="[{ required: true, trigger: 'onSubmit', message: $mt('Please enter password') }]">
              <template #left-icon>
                <van-icon name="lock" size="22px" color="#fff" />
              </template>
              <!-- 登录按钮 -->
              <template #button>
                <div
                  @click="handleLogin"
                  class="flex h-8 w-12 items-center justify-center rounded-full cursor-pointer bg-red1">
                  <van-icon name="arrow" color="#fff" size="20px" />
                </div>
              </template>
            </van-field>
          </div>
        </van-form>
      </div>
      <!-- 修改密码 -->
      <div @click="changePassEl.showDialog()" class="flex items-center justify-center lg:mb-8 mb-5 cursor-pointer">
        <span class="text-red1 text-center">{{ $mt('Forgot password') }}?</span>
      </div>
      <div class="flex justify-center mb-4">
        <GoogleSignInButton @success="handleGoogleLogin" @error="handleLoginError" />
      </div>
    </template>

    <template #info>
      <p class="my-2.5 text-sm lg:mb-3.5 lg:mt-[0] lg:text-2xl lg:font-[600]">
        {{ $mt('ONE ACCOUNT FOR ALL BitTopup SERVICES') }}
      </p>
      <p class="leading-[1.5] text-[#ac8f8f] lg:mb-1 lg:text-base">
        {{ $mt(' Hi there! Sign up an account and enjoy your shopping experience on BitTopup.') }}
      </p>
      <button
        name="button"
        @click="
          $softReplaceRoute({
            path: '/sso/register',
            query: {
              redirectTo: route.query.redirectTo,
            },
          })
        "
        class="mx-auto mt-5 flex h-9 w-[200px] items-center justify-center rounded-3xl bg-red1 lg:mx-0 lg:text-base">
        <span class="font-[500]">{{ $mt('CREATE NEW ACCOUNT') }}</span>
      </button>
    </template>
  </LoginLayout>
  <LoginChangePassDialog @pwdChange="($event) => (formData.password = $event)" ref="changePassEl" />
</template>

<script setup lang="ts">
import { useRequest } from '~/composables/useRequest'
import { pattern, validator } from '~/utils'
import { useMemberStore } from '~/store/member'
import { decodeCredential, GoogleSignInButton } from 'vue3-google-signin'
import type { CredentialResponse } from 'vue3-google-signin'

useSeoMeta({ title: 'BitTopup - Login Center' })

const changePassEl = ref()
//
const route = useRoute()
const memberStore = useMemberStore()
const { $mt, $forceReplaceRoute } = useCommonPlugin()
const { withLoadingToastRef } = useRequestLoading()
const formData = ref({
  email: '',
  password: '',
})
const formRef = ref()
definePageMeta({
  layout: 'plain',
})
//
const { requestGet, requestPost } = useRequest()
// 登录
const handleLogin = async () => {
  await formRef.value.validate()
  const result = await requestPost('/app/sso/login', formData.value)
  if (result.data.notExist) {
    await showConfirmDialog({
      message: $mt('Your account does not exist, would you like to register now?'),
      cancelButtonText: 'Cancel',
      confirmButtonText: 'Confirm',
    })
    return handleRegister()
  }
  localStorage.setItem('authToken', result.data.token)
  showToast($mt('Login Successful'))
  await memberStore.updateMemberProfile(result.data.user)
  await $forceReplaceRoute((route.query.redirectTo ? route.query.redirectTo : '/') as any)
}
withLoadingToastRef()
// handle success event
const handleGoogleLogin = async (response: CredentialResponse) => {
  const { credential } = response
  const { email, name, picture, id } = decodeCredential(credential)
  const result = await requestPost('/app/sso/loginByOpenid', { openid: id, email, name, picture })
  localStorage.setItem('authToken', result.data.token)
  showToast($mt('Login Successful'))
  await memberStore.updateMemberProfile(result.data.user)
  await $forceReplaceRoute((route.query.redirectTo ? route.query.redirectTo : '/') as any)
}
const handleRegister = async () => {
  const { data } = await requestPost('/app/sso/register', formData.value)
  localStorage.setItem('authToken', data.token)
  await memberStore.updateMemberProfile(data.user)
  showToast($mt('Sign up Successful'))
  await $forceReplaceRoute((route.query.redirectTo ? route.query.redirectTo : '/') as any)
}
// handle an error event
const handleLoginError = () => {
  showToast($mt('Google login failed'))
}
</script>

<style lang="scss"></style>
